<template>
	<el-tree ref="treeRef" style="max-width: 600px" :data="data" show-checkbox default-expand-all node-key="id"
		highlight-current :props="defaultProps" :default-checked-keys="checkedMenus" />
	<hr />
	<el-button type="primary" @click="submitForm()">保存</el-button>
	<el-button @click="resetForm()">重置</el-button>

</template>
<script lang="ts" setup>
	import { ref, onMounted } from 'vue'
	import { ElTree } from 'element-plus'
	import type Node from 'element-plus/es/components/tree/src/model/node'
	import rolemenuapi from "../../api/rolemenuapi"
	import { ElNotification } from 'element-plus'

	const defaultProps = {
		children: 'children',
		label: 'label',
	}
	const props = defineProps({
		Id: Number,
	});
	const emit = defineEmits(['onSave'])

	interface Tree {
		id : number
		label : string
		children ?: Tree[]
	}

	const treeRef = ref<InstanceType<typeof ElTree>>()
	const data = ref<Tree[]>([]);
	const checkedMenus = ref([])

	const getdata = () => {
		rolemenuapi.Tree({}).then(res => {
			console.log("restree", res.data);
			data.value = res.data
		})
	}

	const getRoleMenus = () => {
		rolemenuapi.rolemenu({ RoleId: props.Id }).then(res => {
			console.log("eee", res.data);
			checkedMenus.value = []
			res.data.forEach(item => {
				checkedMenus.value.push(item.MenuId)
			})
		})
	}

	onMounted(() => {
		getdata();
		getRoleMenus();
	})

	const submitForm = () => {

		var menus = treeRef.value!.getCheckedKeys(true);

		var data = { RoleId: props.Id, MenuIds: menus };
		console.log("data", data)

		rolemenuapi.batch(data).then(res => {
			if (res.code == 1) {
				ElNotification({
					title: 'Success',
					message: '授权成功',
					type: 'success',
					duration: 800,
					onClose: () => {
						emit("onSave", true)
					}
				})
			} else {
				ElNotification({
					title: 'Error',
					message: '失败',
					type: 'Error',
					duration: 800,
				})
			}
		})
	}
	const resetForm = () => {
		getRoleMenus();
	}
</script>

<style>
</style>